/*
 * Copyright (C) 2010-2012 Enrique Lara (enrique.posix2.lara@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
 * limitations under the License.
  */
package app.transitalarm.model;

import app.transitalarm.util.Log;

public final class Matcher {
    private static final String TAG = "Matcher";
    private final Alarm a;

    public Matcher(final Alarm a) {
        this.a = a;
    }

    public boolean isInRange(final Vehicle t) {
        boolean inRange = false;

        if (lineMatches(t)) {
            if (directionMatches(t)) {
                if (t.getMinutes() <= a.getMaxTime()) {
                    if (t.getMinutes() >= a.getMinTime()) {
                        inRange = true;
                    } else {
                        Log.d(TAG, String.format("%1d is not lte %2d.  Not enough lead time.", a.getMinTime(), t.getMinutes()));
                    }
                } else {
                    Log.d(TAG, String.format("%1d is not gte %2d. Too far away.", a.getMaxTime(), t.getMinutes()));
                }
            } else {
                Log.d(TAG, String.format("%1s<>%2s.  Wrong direction.", a.getDirection(), t.getDestinationCode()));
            }
        } else {
            Log.d(TAG, String.format("%1s<>%2s. Wrong line.", a.getRouteCode(), t.getLine()));
        }

        return inRange;
    }

    private boolean lineMatches(final Vehicle t) {
        return equalsIgnoreCase(a.getRouteCode(), t.getLine());
    }

    private boolean directionMatches(final Vehicle t) {
        return equalsIgnoreCase(a.getDirection(), t.getDestinationCode());
    }

    private static boolean equalsIgnoreCase(final String s1, final String s2) {
        return (s1 != null) ? s1.equalsIgnoreCase(s2) : (s2 == null);
    }
}
